<template>
  <div>
    <h3>商品管理 - 删除商品</h3>
    <el-form :model="deleteDto" ref="deleteForm" label-width="120px">
      <el-form-item label="选择店铺" prop="merchantId">
        <el-select v-model="deleteDto.merchantId" placeholder="请选择店铺" @change="getProductsByMerchant">
          <el-option
              v-for="merchant in merchantList"
              :key="merchant.id"
              :label="merchant.shopName"
              :value="merchant.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="选择商品" prop="id">
        <el-select v-model="deleteDto.id" placeholder="请选择商品">
          <el-option
              v-for="product in productList"
              :key="product.id"
              :label="product.name"
              :value="product.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="deleteProduct">删除商品</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 从 localStorage 获取用户信息
const userStr = localStorage.getItem('merchant');
const user = userStr ? JSON.parse(userStr) : null;

// 定义删除表单数据
const deleteDto = ref({
  id: null,
  merchantId: null
});

// 表单引用
const deleteForm = ref(null);

// 定义店铺列表
const merchantList = ref([]);

// 定义商品列表
const productList = ref([]);

// 获取店铺列表
const getMerchantList = async () => {
  try {
    // 发送查看店铺请求
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selStore`, {
      withCredentials: true
    });
    if (response.data.code === 2000) {
      merchantList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取店铺列表失败');
    }
  } catch (error) {
    console.error('获取店铺列表失败:', error);
    ElMessage.error('获取店铺列表失败，请稍后重试');
  }
};

// 根据店铺 ID 获取商品列表
const getProductsByMerchant = async () => {
  const merchantId = deleteDto.value.merchantId;
  if (!merchantId) return;
  try {
    const response = await axios.get(`${BASE_URL}/api/v1/merchant/selProduct`, {
      params: { merchantId },
      withCredentials: true
    });
    if (response.data.code === 2000) {
      productList.value = response.data.data;
    } else {
      ElMessage.error(response.data.msg || '获取商品列表失败');
    }
  } catch (error) {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败，请稍后重试');
  }
};

// 定义删除商品方法
const deleteProduct = async () => {
  // 表单验证
  deleteForm.value.validate(valid => {
    if (!valid) {
      ElMessage.error('请完善删除信息');
      return;
    }

    // 发送删除商品请求
    axios.post(`${BASE_URL}/api/v1/merchant/delProduct`, deleteDto.value, {
      withCredentials: true
    })
        .then(response => {
          if (response.data.code === 2000) {
            ElMessage.success('商品删除成功');
            // 清空表单
            deleteDto.value = {
              id: null,
              merchantId: null
            };
            productList.value = [];
          } else {
            ElMessage.error(response.data.msg || '删除商品失败');
          }
        })
        .catch(error => {
          console.error('删除商品失败:', error);
          ElMessage.error('删除商品失败，请稍后重试');
        });
  });
};

// 页面挂载时获取店铺列表
onMounted(() => {
  if (user) {
    getMerchantList();
  } else {
    ElMessage.error('请先登录');
  }
});
</script>

<style scoped>
/* 可以根据需要添加样式 */
</style>